home *** CD-ROM | disk | FTP | other *** search
/ Aminet 22 / Aminet 22 (1997)(GTI - Schatztruhe)[!][Dec 1997].iso / Aminet / dev / e / amigae33a.lha / E_v3.3a / Src.lha / Src / Tools / Useful / split.e < prev    next >
Text File  |  1995-12-14  |  2KB  |  63 lines

  1. OPT MODULE
  2.  
  3. ENUM A_BEGIN, A_SPACE, A_QUOTE, A_QUOTE2, A_END
  4.  
  5. CONST NUM="\a"+1
  6.  
  7. -> Split the string "str" (which defaults to the arguments string "arg")
  8. EXPORT PROC argSplit(str=NIL) IS splitStr_(IF str THEN str ELSE arg)
  9.  
  10. -> A small function to split an argument string like "arg" into a C-like array
  11. -> of arguments, handling quoted arguments properly.  Uses recursion to collect
  12. -> list contents, then allocate list and set contents.  Result is NIL if out of
  13. -> memory, or an E-list of pointers to (normal) strings (this list is also NIL
  14. -> terminated so you have a choice of how to use it).  The original string is
  15. -> effectively destroyed and should not be used after calling this function.
  16. PROC splitStr_(str, len=0)
  17.   DEF tmp=A_BEGIN:PTR TO LONG, s  -> Reuse tmp to save stack space
  18.   s:=str
  19.   WHILE tmp<>A_END
  20.     SELECT NUM OF str[]
  21.     CASE 0, "\n", "\b"
  22.       IF tmp=A_BEGIN THEN s:=NIL
  23.       str[]:=0
  24.       tmp:=A_END
  25.     CASE "\q"
  26.       SELECT A_END OF tmp
  27.       CASE A_BEGIN; tmp:=A_QUOTE; s++
  28.       CASE A_QUOTE; tmp:=A_END;   str[]:=0
  29.       ENDSELECT
  30.       str++
  31.     CASE "\a"
  32.       SELECT A_END OF tmp
  33.       CASE A_BEGIN;  tmp:=A_QUOTE2; s++
  34.       CASE A_QUOTE2; tmp:=A_END;    str[]:=0
  35.       ENDSELECT
  36.       str++
  37.     CASE " ", "\t"
  38.       SELECT A_END OF tmp
  39.       CASE A_BEGIN;  s++
  40.       CASE A_SPACE;  tmp:=A_END; str[]:=0
  41.       ENDSELECT
  42.       str++
  43.     DEFAULT
  44.       IF tmp=A_BEGIN THEN tmp:=A_SPACE
  45.       str++
  46.     ENDSELECT
  47.   ENDWHILE
  48.   IF s  -> If not the last one...
  49.     IF FreeStack()>=1000  -> (Check stack since recursing...)
  50.       tmp:=splitStr_(str, len+1)  -> ... split the rest,
  51.       IF tmp THEN tmp[len]:=s   -> and add this one in
  52.     ELSE
  53.       tmp:=NIL
  54.     ENDIF
  55.   ELSE  -> Else reached the end of arg...
  56.     tmp:=List(len+1)  -> ... allocate list and set length
  57.     IF tmp            -> (Extra element is for NIL termination)
  58.       tmp[len]:=NIL
  59.       SetList(tmp, len)
  60.     ENDIF
  61.   ENDIF
  62. ENDPROC tmp  -> Returns NIL if List() fails
  63.